package com.deli.surfacedemo;

import android.app.Activity;
import android.content.Context;
import android.content.Loader;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

public class SecondActivity extends AppCompatActivity {

    MySurfaceView surfaceView;
    Camera mCamera;
    int width=0;
    int height=0;
    float scale=0;
    View saomiaoView;
    ImageView img;
    Canvas mCanvas;
    Paint mPaint;
    View kuangView;

    Camera.PreviewCallback previewCallback;
    private Camera.AutoFocusCallback myAutoFocusCallback = null;
    //其中 mCameraId 是当前使用的 CameraId, 一般前置为1， 后置为 0。


    Handler handler=new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            if(msg.arg1==1000)
            {
                mCamera.setOneShotPreviewCallback(previewCallback);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        WindowManager wm = this.getWindowManager();

        //后面转移到启动页
        width=wm.getDefaultDisplay().getWidth();
        height=wm.getDefaultDisplay().getHeight();
        scale=this.getResources().getDisplayMetrics().density;

        mPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStrokeWidth(5);
        mPaint.setColor(Color.YELLOW);
        mPaint.setStyle(Paint.Style.STROKE);

        initView();
        initData();
        initEvent();
    }

    private void initView() {
        saomiaoView= (View) findViewById(R.id.saomiao_view);
        kuangView=findViewById(R.id.kuang_view);
          RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) kuangView.getLayoutParams();
        params.height=(int) ((width-40*scale)/3*2);
        params.width=(int) (width-40*scale);
        kuangView.setLayoutParams(params);

        surfaceView= (MySurfaceView) findViewById(R.id.surface_view);
        img= (ImageView) findViewById(R.id.img);


        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(final SurfaceHolder surfaceHolder) {
                try {
                    mCamera=getCameraInstance();
                }catch (Exception e){}

                setParams(mCamera);
                setCameraDisplayOrientation(SecondActivity.this,0,mCamera);
                try {
                    mCamera.setPreviewDisplay(surfaceView.getHolder());
                    mCamera.startPreview();
                    Log.e("111",11+"");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

            }
        });

       // mCamera.startPreview(); // 打开预览画面
        TranslateAnimation animation=new TranslateAnimation(0,0,0,width-120*scale);
        animation.setDuration(3000);
        animation.setRepeatMode(Animation.REVERSE);//设置反方向执行
        animation.setRepeatCount(500);
        saomiaoView.setAnimation(animation);
        animation.start();
        myAutoFocusCallback = new Camera.AutoFocusCallback() {

            public void onAutoFocus(boolean success, Camera camera) {
                // TODO Auto-generated method stub
                if(success)//success表示对焦成功
                {
                    Log.i("success", "myAutoFocusCallback: success...");
                    //myCamera.setOneShotPreviewCallback(null);
                }
                else
                {
                    //未对焦成功
                    Log.i("success", "myAutoFocusCallback: 失败了...");
                }
            }
        };

        previewCallback=new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] bytes, Camera camera) {
                //Toast.makeText(TestActivity.this,"11",Toast.LENGTH_SHORT).show();
                Bitmap bitmap=byte2bitmap(bytes,camera);
                img.setImageBitmap(bitmap);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                            try {
                                mCamera.autoFocus(myAutoFocusCallback);//调自动对角
                            }catch (Exception e)
                            {}
                            Message msg=Message.obtain();
                            msg.arg1=1000;
                            handler.sendMessage(msg);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        };
    }

    //访问相机
    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(0); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    private void initData() {
    }

    private void initEvent() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    try {
                        mCamera.autoFocus(myAutoFocusCallback);//调自动对角
                    }catch (Exception e)
                    {}
                    Message msg=Message.obtain();
                    msg.arg1=1000;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //设置属性
    private void setParams(Camera mCamera)
    {
        if(mCamera==null)
        {
            return;
        }
        Camera.Parameters parameters = mCamera.getParameters();
        // parameters.setFlashMode("off"); // 无闪光灯
        parameters.setPictureFormat(PixelFormat.JPEG); //Sets the image format for picture 设定相片格式为JPEG，默认为NV21
        parameters.setPreviewFormat(PixelFormat.YCbCr_420_SP);
        // 设置拍照和预览图片大小
        int size=(int) (width-125*scale);

       Camera.Size preSize = getCloselyPreSize(true,width,height, parameters.getSupportedPreviewSizes());
       /* RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) surfaceView.getLayoutParams();
        params.height=(int) (width-80*scale);
        params.width=(int) ((width-80*scale)/(preSize.width/(float)preSize.height));
        surfaceView.setLayoutParams(params);*/
        parameters.setPictureSize(preSize.width,preSize.height); //指定拍照图片的大小
        parameters.setPreviewSize(preSize.width,preSize.height); // 指定preview的大小
        //Log.d("pre",preSize.width+"   "+preSize.height+"   "+(int) ((width-80*scale)/(preSize.width/(float)preSize.height)));
        //这两个属性 如果这两个属性设置的和真实手机的不一样时，就会报错
        // 横竖屏镜头自动调整
        if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
        {
            parameters.set("orientation", "portrait"); //
            parameters.set("rotation", 90); // 镜头角度转90度（默认摄像头是横拍）
            mCamera.setDisplayOrientation(90); // 在2.2以上可以使用
        } else// 如果是横屏
        {
            parameters.set("orientation", "landscape"); //
            mCamera.setDisplayOrientation(0); // 在2.2以上可以使用
            // 设定配置参数并开启预览
            mCamera.setParameters(parameters); // 将Camera.Parameters设定予Camera
            //mCamera.startPreview();
        }
    }

    public static  Camera.Size getCloselyPreSize(boolean isPortrait, int surfaceWidth, int surfaceHeight, List<Camera.Size> preSizeList) {
        int reqTmpWidth;
        int reqTmpHeight;
        // 当屏幕为垂直的时候需要把宽高值进行调换，保证宽大于高
        if (isPortrait) {
            reqTmpWidth = surfaceHeight;
            reqTmpHeight = surfaceWidth;
        } else {
            reqTmpWidth = surfaceWidth;
            reqTmpHeight = surfaceHeight;
        }
        //先查找preview中是否存在与surfaceview相同宽高的尺寸
        for(Camera.Size size : preSizeList){
            if((size.width == reqTmpWidth) && (size.height == reqTmpHeight)){
                return size;
            }
        }

        // 得到与传入的宽高比最接近的size
        float reqRatio = ((float) reqTmpWidth) / reqTmpHeight;
        float curRatio, deltaRatio;
        float deltaRatioMin = Float.MAX_VALUE;
        Camera.Size retSize = null;
        for (Camera.Size size : preSizeList) {
            curRatio = ((float) size.width) / size.height;
            deltaRatio = Math.abs(reqRatio - curRatio);
            if (deltaRatio < deltaRatioMin) {
                deltaRatioMin = deltaRatio;
                retSize = size;
            }
        }

        return retSize;
    }


    public static void setCameraDisplayOrientation(Activity activity,
                                                   int cameraId, android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }


    private Bitmap byte2bitmap(byte[] bytes, Camera camera) {
        Bitmap bitmap = null;

        Camera.Size size = camera.getParameters().getPreviewSize(); // 获取预览大小
        final int w = size.width; // 宽度
        final int h = size.height;
        final YuvImage image = new YuvImage(bytes, ImageFormat.NV21, w, h,
                null);
        ByteArrayOutputStream os = new ByteArrayOutputStream(bytes.length);
        if (!image.compressToJpeg(new Rect(0, 0, w, h), 100, os)) {
            return null;
        }
        byte[] tmp = os.toByteArray();
        bitmap = BitmapFactory.decodeByteArray(tmp, 0, tmp.length);


       /* android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(0, info);*/
        float bili=(float)width/size.height;

        Matrix matrix = new Matrix();
        matrix.setRotate(getOrientation(SecondActivity.this));
        int w1=(int)((width-40*scale)/bili);
        int h1=(int)(w1/3*2);
        bitmap = Bitmap.createBitmap(bitmap,0,0,size.width,size.height,matrix,true);
       // mCanvas.drawRect(20*scale,(height-(width-40*scale)/3*2)/2,width-20*scale,(height+(width-40*scale)/3*2)/2,mPaint);
        bitmap = Bitmap.createBitmap(bitmap,(int)(20*scale/bili),(int)((bitmap.getHeight()-h1)/2),w1,h1,null,true);
       // Bitmap bitmap1 = rotateBitmap(bitmap, info.orientation);

       // Log.d("222",w1+"   "+h1);
         Log.d("222",(int)(20*scale/bili)+"   "+ (int)((bitmap.getHeight()-h1)/2)+"  "+(int) ((width-20*scale)/bili)+"   "+(int) ((bitmap.getHeight()+h1))/2);
        return bitmap;
    }



    public static int getOrientation(Context context) {
        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int rotation = display.getRotation();
        int orientation;
        boolean expectPortrait;
        switch (rotation) {
            case Surface.ROTATION_0:
            default:
                orientation = 90;
                expectPortrait = true;
                break;
            case Surface.ROTATION_90:
                orientation = 0;
                expectPortrait = false;
                break;
            case Surface.ROTATION_180:
                orientation = 270;
                expectPortrait = true;
                break;
            case Surface.ROTATION_270:
                orientation = 180;
                expectPortrait = false;
                break;
        }
        boolean isPortrait = display.getHeight() > display.getWidth();
        if (isPortrait != expectPortrait) {
            orientation = (orientation + 270) % 360;
        }
        return 0-orientation;
    }
}
